(function() {
    "use strict";
    var app = angular.module("angularApp");
    app.directive("treeMenu", function() {
        return {
            restrict: "E",
            scope: {
                nodeList: '=',
                pnode: "=",
                config:"<?"
            },
            templateUrl: 'common/treeMenu.html',
            controller: function($scope) {
                $scope.selectMenu = $scope.$parent.selectMenu;
            }
        };
    });

    app.config(['$uibModalProvider', function($uibModalProvider) {
        $uibModalProvider.options = { backdrop: 'static', keyboard: true };
    }]);

    // 控制器
    app.controller('mainController', function($scope, $rootScope, $location, $q, $http, $uibModal, $state,fac,commonControllers) {
        //$scope.menus = appData.menus;
        var menuData;
        $rootScope.scene = {};
        $scope.menuConfig = $scope.menuConfig||{collapse:localStorage.getItem("menuCollapse")=="true"||false};
        $scope.toggleCollapse = function(){
            $scope.menuConfig.collapse = !$scope.menuConfig.collapse;
            localStorage.setItem("menuCollapse",$scope.menuConfig.collapse);
        }
        function getLoginUser() {
            var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
            $http.get("../free/getUserInfo").success(function(resp) {
                 if(resp.code == 0){
                     app.user = $rootScope.user = resp.data.user;
                     $rootScope.menus = resp.data.menus;
                     resp.data.allDict.forEach(dict=>$rootScope[dict.type]=eval(dict.jsonStr));
                     menuData = fac.treeToFlat($rootScope.menus);
                     deferred.resolve(resp.data);
                 }  else {
                     location.href = "login.html";
                 }
            })
            return deferred.promise; // 返回承诺，这里并不是最终数据，而是访问最终数据的API
        }

        //退出
        $scope.logout = function() {
            $http.get("../free/logout").success(function(resp) {
                location.href = "login.html";
            })
        };

        //获取所有枚举
        app.loginPromise = getLoginUser();
      /*  app.loginPromise.then(function(){
            !app.sceneTree && $http.get("../scene/sceneTree").success(function(resp){
                if(resp.code == 0){
                    app.sceneTree = resp.data;
                    $rootScope.filteredSceneTree = $.extend(true, [],app.sceneTree);
                    $rootScope.flatSceneTree = fac.treeToFlat($rootScope.filteredSceneTree);
                    //选中之前选中的部门
                    var lastSceneId =   localStorage.getItem("lastSceneId");
                    var scene = lastSceneId?$rootScope.flatDetpTree.find(function(n){return n.id == lastSceneId}):null;
                    //如果部门为空，当前部门选中第一个根节点！
                    if(!scene && $rootScope.filteredSceneTree.length>0){
                        scene = $rootScope.filteredSceneTree[0];
                    }
                    scene.state = {selected:true};
                    angular.extend($rootScope.scene,{id:scene.id,pid:scene.pid,sceneName:scene.text});
                }
            });

            if("/welcome" == $location.$$url){
                $location.url("/icon/icon");
            }
        })*/

      //  app.modulePromiss = $q.all([app.loginPromise]);
        //  app.modulePromiss =
        //app.modulePromiss = $q.all([deferModule, deferParkTree.promise]);
        $rootScope.$on('$stateChangeSuccess', function (evt, toState, toParams, fromState, fromParams) {
            var newUrl = toState.url;
            function toMenu (){
                var item;
                //如果是三级菜单
                if (toParams.catalogue) {
                    item = menuData.find(function (n) {
                        return n.url == toParams.folder + "/" + toParams.catalogue + "/" + toParams.page
                    });
                } else {
                    item = menuData.find(function (n) {
                        return n.url == toParams.folder + "/" + toParams.page
                    });
                }
                if (item) {
                    $scope.selectMenu(item);
                    if (!$rootScope.hasPower('编辑')) {
                        $rootScope.config = {edit: true};
                    } else {
                        $rootScope.config = {edit: true};
                    }
                }
            }
            if (toParams.folder && toParams.page) {
                // zg 避免权限验证 begin
                $rootScope.config = {edit: true};
                // end
                app.loginPromise.then(function(user){
                    toMenu();
                })
            }
            $rootScope.$broadcast('destory');  //销毁video实例
        })

        $scope.selectMenu = function (node) {
            function _isAncestorNode(parent, son) {
                if (son.pids && son.pids.split(",").indexOf(parent.id + "") > -1) {
                    return true;
                }
                return false;
            }

            var otherExpandMenu = menuData.find(function (n) {
                return n.expanded == true && n != node && !_isAncestorNode(n, node)
            })
            otherExpandMenu && (otherExpandMenu.expanded = false);

            if (node.nodes && node.nodes.length) {
                node.expanded = !node.expanded;
            } else {
                //展开父节点
                menuData.forEach(function (n) {
                    if (_isAncestorNode(n, node)) {
                        n.expanded = true;
                    }
                })
                //叶子节点
                if ($scope.curMenu && $scope.curMenu != node) {
                    $scope.curMenu.selected = false;
                }
                node.selected = true;
                //$location.url(node.url);
                app.powers = node.powers;
                //$state.go(node.url);

                var urls = node.url.split('/');
                if (urls.length === 2) {
                    $state.go('admin', { folder: urls[0], page: urls[1] });
                } else if (urls.length === 3) {
                    $state.go('three', { folder: urls[0], catalogue: urls[1], page: urls[2] });
                }

                $rootScope.curMenu = node;
                document.body.scrollTop = document.documentElement.scrollTop = 0;
            }
        }

        $(document).bind("keydown keypress", function (event) {
            if(event.which === 13) {

                if($("#content").length <= 0 && $("textarea:focus,:button:focus,.btn:focus").length <= 0) {
                    var buttons = $(".btn:contains('查询')");
                    for(var i=0;i<buttons.length;i++){
                        var button = buttons[i];
                        if($(button).closest('*:hidden').length){
                            continue;
                        }
                        $(button).trigger("click");
                        break;
                    }
                    event.preventDefault();
                }
            }
        });
    });

})();
